<template>
  <el-card>
    <tableCommon ref="table" url="/file" :default-tool-bar="false">
      <template #toolbar />
      <el-table-column prop="objectName" label="文件名" />
      <template #operating>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              :disabled="hasDisabled(scope.row)"
              title="下载"
              type="primary"
              icon="el-icon-download"
              circle
              size="small"
              @click="handleDownload(scope.row)"
            />
          </template>
        </el-table-column>
      </template>
    </tableCommon>
  </el-card>
</template>

<script>
import client from '@/plugins/ossClient'

export default {
  methods: {
    hasDisabled(row) {
      if (row.serverType === 'oss') {
        return false
      } else {
        return true
      }
    },
    handleDownload(row) {
      const objectName = row.objectName
      // 校验文件是否存在
      client.get(objectName).then((result) => {
        if (result.res.status === 200) {
          // 获取文件下载路径
          const url = client.signatureUrl(objectName, {
            response: {
              'content-disposition': 'attachment; filename=' + row.name
            }
          })
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '')
          document.body.appendChild(link)
          link.click()
        }
      }).catch((e) => {
        if (e.code === 'NoSuchKey') {
          this.$message.error('文件不存在')
        }
      })
    }
  }
}
</script>

<style>
</style>
